package com.esender.strategy.filter.impl;

import com.esender.common.constant.CacheConstant;
import com.esender.common.constant.RabbitMQConstants;
import com.esender.common.enums.MobileOperatorEnum;
import com.esender.common.model.StandardSubmit;
import com.esender.strategy.client.BeaconCacheClient;
import com.esender.strategy.filter.StrategyFilter;
import com.esender.strategy.util.MobileOperatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service(value = "phase")
@Slf4j
public class PhaseStrategyFilter implements StrategyFilter {
    private static final int MOBILE_START = 0;
    private static final int MOBILE_END = 7;

    private static final String SEPARATOR = ",";
    private static final int LENGTH = 2;
    private static final String UNKNOWN = "未知 未知,未知";
    @Autowired
    private BeaconCacheClient beaconCacheClient;
    @Autowired
    private MobileOperatorUtil mobileOperatorUtil;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public void strategy(StandardSubmit standardSubmit){
        log.info("【策略模块-号段补全校验】   校验ing…………");
        String mobile = standardSubmit.getMobile().substring(MOBILE_START, MOBILE_END);
        String mobileInfo = beaconCacheClient.get(CacheConstant.PHASE + mobile);

        getMobileInfo : if (StringUtils.isBlank(mobileInfo)){
            log.info("【策略模块-号段补全校验】   校验ing-缓存为空，调用第三方接口…………");
            mobileInfo = mobileOperatorUtil.getMobileInfo(mobile);
            if (StringUtils.isNotBlank(mobileInfo)){
                // TODO：调用第三方接口查询到信息以后，发送消息到MQ，并且同步到mysql和redis
                rabbitTemplate.convertAndSend(RabbitMQConstants.MOBILE_AREA_OPERATOR,standardSubmit.getMobile());
                break getMobileInfo;
            }
            // 第三方都没有查询到信息
            mobileInfo = UNKNOWN;
        }
        // 查询到以后封装到standardSubmit
        String[] areaAndOperator = mobileInfo.split(SEPARATOR);
        if (areaAndOperator.length == LENGTH){
            standardSubmit.setArea(areaAndOperator[0]);
            standardSubmit.setOperatorId(MobileOperatorEnum.getMobileOperator(areaAndOperator[1]).getOperatorId());
        }
    }
}
